package com.shareach.web.util;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;

import com.benayn.ustyle.logger.Loggers;
import com.shareach.common.BizCondition;
import com.shareach.dao.redis.impl.DeployRDao;
import com.shareach.dao.redis.impl.DeployRDao.DeployType;
import com.shareach.dao.redis.impl.MatchRDao;
import com.shareach.domain.BaseCityDomain;
import com.shareach.domain.BizActivityDomain;
import com.shareach.domain.BizActivityShopDomain;
import com.shareach.domain.DiscountType;
import com.shareach.service.BaseCityService;
import com.shareach.service.BizActivityService;
import com.shareach.service.BizActivityShopService;
import com.shareach.util.ExcelParseState;
import com.shareach.util.ExcelParseState.State;
import com.shareach.util.Globals;

/**
 * create time：2013-1-25 下午1:05:44
 * 
 * @author retryu
 * @since JDK 1.6
 * @version 1.0 description：
 */
public class ParseExcelUtil {
	private static final Log log = Loggers.from(ParseExcelUtil.class);
	
	public static HttpClient client;
	public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat dateFormat_2 = new SimpleDateFormat("M/dd/yy");
	public static ExcelParseState excelParseState;
	private File excleFile;
	private Sheet[] sheets;
	BizActivityService activityService;
	BizActivityShopService shopService;
	BaseCityService cityService;
	String os = System.getProperty("os.name");
	private MatchRDao matchRDao;
	private DeployRDao deployRDao;

	HashMap<String, ActivityShop> data;
	BizActivityDomain activity;

	public MatchRDao getMatchRDao() {
		return matchRDao;
	}

	public void setMatchRDao(MatchRDao matchRDao) {
		this.matchRDao = matchRDao;
	}

	public void initParsingState(Sheet[] sheets) {
		excelParseState = new ExcelParseState();
		for (int i = 0; i < sheets.length; i++) {
			State state = excelParseState.addState();
			state.name = sheets[i].getName();
			state.current = 0;
		}
	}

	public ParseExcelUtil(File file, BizActivityService activityService, BizActivityShopService shopService,
			BaseCityService cityService, MatchRDao matchRDao) {
		this(file, activityService, shopService, cityService, matchRDao, null);
	}

	public ParseExcelUtil(File file, BizActivityService activityService, BizActivityShopService shopService,
			BaseCityService cityService, MatchRDao matchRDao, DeployRDao deployRDao) {
		this.cityService = cityService;
		this.activityService = activityService;
		this.shopService = shopService;
		this.matchRDao = matchRDao;
		excleFile = file;
		client = new HttpClient();
		this.deployRDao = deployRDao;
		parsing();
	}

	/**
	 * 解析Excle
	 */
	public void parsing() {
		try {
			Workbook workbook = Workbook.getWorkbook(excleFile);
			sheets = workbook.getSheets();
			initParsingState(sheets);
			excelParseState.PrintState();

			for (int count = 0; count < sheets.length; count++) {
				data = new HashMap<String, ActivityShop>();
				Sheet sheet = sheets[count];

				int rows = sheet.getRows();
				int columns = sheet.getColumns();
				if (rows == 0 && columns == 0)
					continue;

				ArrayList<BizActivityShopDomain> activityShops = new ArrayList<BizActivityShopDomain>();

				activity = new BizActivityDomain();
				parseActivity(sheet, activity);

				for (int i = 3; i < rows; i++) {
					parseShops(sheet, i, activityShops, activity);
				}

				save();
				System.err.println("当前Sheet全部处理完毕-------------------------------------" + sheet.getName());
			}
			System.err.println("全部excel处理完毕-------------------------------------");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class ActivityShop {
		BizActivityDomain activity;
		ArrayList<BizActivityShopDomain> actiivtyShops;
	}

	public void parseActivity(Sheet sheet, BizActivityDomain activity) {

		String title;
		Long bankId;
		String descrption;
		String discountRule;
		Integer[] dayOfWeek = null;
		String keyword;
		String campCat;
		Date start = null;
		Date end = null;
		String campRat;
		String picId;
		String sid;
		try {
			if (!sheet.getCell(0, 1).getContents().equals("")) {
				title = sheet.getCell(0, 1).getContents();
				activity.setTitle(title);

			}
			if (!sheet.getCell(1, 1).getContents().equals("")) {
				try {
					bankId = Long.valueOf(sheet.getCell(1, 1).getContents());
					activity.setBankId(bankId);
				} catch (Exception e) {
					System.err.print("err!!");
					e.printStackTrace();
				}
			}

			if (!sheet.getCell(2, 1).getContents().equals("")) {
				if (os.startsWith("Linux")) {
					start = dateFormat_2.parse(sheet.getCell(2, 1).getContents());
				} else {
					String startTime = "20" + sheet.getCell(2, 1).getContents();
					start = dateFormat.parse(startTime);
				}
				activity.setStart(start);
			}
			if (!sheet.getCell(3, 1).getContents().equals("")) {
				if (os.startsWith("Linux")) {
					end = dateFormat_2.parse(sheet.getCell(3, 1).getContents());
				} else {
					String endTime = "20" + sheet.getCell(3, 1).getContents();
					end = dateFormat.parse(endTime);
				}
				activity.setEnd(end);
			}
			if (!sheet.getCell(4, 1).getContents().equals("")) {
				String content = sheet.getCell(4, 1).getContents();
				if (content.equals("all")) {
					dayOfWeek = new Integer[7];
					for (int i = 0; i < 7; i++) {
						dayOfWeek[i] = i + 1;
					}
				} else if (!content.equals("指定日")) {
					String[] days = content.split("/");
					dayOfWeek = new Integer[days.length];
					for (int i = 0; i < days.length; i++) {

						dayOfWeek[i] = parseDayOfWeek(days[i]);
					}
				}
				if (dayOfWeek != null)
					activity.setDiscountWeek(dayOfWeek);
			}

			if (!sheet.getCell(6, 1).getContents().equals("")) {
				descrption = sheet.getCell(6, 1).getContents();
				activity.setDescr(descrption);

			}
			if (!sheet.getCell(7, 1).getContents().equals("")) {
				discountRule = sheet.getCell(7, 1).getContents();
				activity.setDiscountRule(discountRule);
			}
			// keyword
			if (!sheet.getCell(8, 1).getContents().equals("")) {
				keyword = sheet.getCell(8, 1).getContents();
				activity.setKeyword(keyword);
			}
			// cat
			if (!sheet.getCell(9, 1).getContents().equals("")) {
				campCat = sheet.getCell(9, 1).getContents();
				activity.setCampCat(campCat);
			}
			// rate
			if (!sheet.getCell(10, 1).getContents().equals("")) {
				campRat = sheet.getCell(10, 1).getContents();
				activity.setCampRat(campRat);
			}
			// pic_id
			if (!sheet.getCell(11, 1).getContents().equals("")) {
				picId = campCat = sheet.getCell(11, 1).getContents();
				activity.setPicId(picId);
			}
			// sid
			if (!sheet.getCell(12, 1).getContents().equals("")) {
				sid = sheet.getCell(12, 1).getContents();
				activity.setSid(sid);
			} else {
				throw new Exception("sid 不能为空");
			}

			ActivityShop activityShop = new ActivityShop();
			activityShop.activity = activity;
			data.put(activity.getCityName(), activityShop);
		} catch (Exception e) {
			e.printStackTrace();
			log.info(activity);
		}
	}

	/**
	 * 解析商户
	 * 
	 * @param sheet
	 * @param index
	 * @param activityShopDomains
	 * @param activityShop
	 */
	public void parseShops(Sheet sheet, int index, ArrayList<BizActivityShopDomain> activityShopDomains,
			BizActivityDomain activityShop) {

		try {
			BizActivityShopDomain shop = new BizActivityShopDomain();
			String cityName = sheet.getCell(1, index).getContents();
			cityName = cityName.replaceAll("[^\u4E00-\u9FA5]", "");
			if (StringUtils.isEmpty(cityName))
				return;
			String orgName = sheet.getCell(3, index).getContents();
			String brandName = sheet.getCell(4, index).getContents();
			String name = sheet.getCell(5, index).getContents();
			String addr = sheet.getCell(6, index).getContents();

			String[] tels = sheet.getCell(7, index).getContents().split("/");
			for (int i = 0; i < tels.length; i++) {
				System.out.print(tels[i] + "  ");
			}

			Integer[] dayOfWeek = null;
			String descript = null;
			String discountRules = null;
			Date start = null;
			Date end = null;

			Long cityId = null;
			BaseCityDomain query = new BaseCityDomain();
			query.setName(cityName);
			List<BaseCityDomain> cities = cityService.getList(query);
			if (cities.size() <= 0) {
				return;
			}
			// System.err.println("city:" + cities.get(0).getCode());
			cityId = cities.get(0).getCode();
			if (!sheet.getCell(8, index).getContents().equals("")) {
				if (os.startsWith("Linux")) {
					start = dateFormat_2.parse(sheet.getCell(8, index).getContents());
				} else {
					String startTime = "20" + sheet.getCell(8, index).getContents();
					start = dateFormat.parse(startTime);
				}
			}
			if (!sheet.getCell(9, index).getContents().equals("")) {
				if (os.startsWith("Linux")) {
					end = dateFormat_2.parse(sheet.getCell(9, index).getContents());
				} else {
					String endTime = "20" + sheet.getCell(9, index).getContents();
					end = dateFormat.parse(endTime);
				}
			}

			if (!sheet.getCell(10, index).getContents().equals("")) {
				String content = sheet.getCell(10, index).getContents();
				if (content.equals("all")) {
					dayOfWeek = new Integer[7];
					for (int i = 0; i < 7; i++) {
						dayOfWeek[i] = i + 1;
					}
				} else {
					String[] days = content.split("/");
					dayOfWeek = new Integer[days.length];
					for (int i = 0; i < days.length; i++) {
						dayOfWeek[i] = parseDayOfWeek(days[i]);
					}
				}

			}
			if (!sheet.getCell(12, index).getContents().equals("")) {
				descript = sheet.getCell(12, index).getContents();
			}

			if (!sheet.getCell(13, index).getContents().equals("")) {
				discountRules = sheet.getCell(13, index).getContents();
			}

			shop.setCity(cityId);
			shop.setCityName(cityName);
			shop.setOrgName(orgName);
			shop.setBrandName(brandName);
			shop.setName(name);
			if (shop.getName().equals("") && shop.getBrandName().equals("")) {
				shop.setName(shop.getOrgName());
			}
			shop.setAddr(addr);
			shop.setTels(tels);
			shop.setDescr(descript);
			shop.setDiscountRule(discountRules);
			if (dayOfWeek != null && dayOfWeek.length > 0) {
				shop.setDiscountWeek(dayOfWeek);
			}
			shop.setStart(start);
			shop.setEnd(end);

			addShop(shop);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addShop(BizActivityShopDomain shop) throws IllegalAccessException, InvocationTargetException {

		if (data.containsKey(shop.getCityName())) {
			ActivityShop activityShop = data.get(shop.getCityName());
			ArrayList<BizActivityShopDomain> shops = activityShop.actiivtyShops;
			// shop.setShopId(activity.getId());
			shop.setActivityId(activityShop.activity.getId());

			shops.add(shop);
		} else {
			ActivityShop activityShop = new ActivityShop();
			BizActivityDomain bizActivity = new BizActivityDomain();
			bizActivity = activityShop.activity;

			try {
				bizActivity = (BizActivityDomain) BeanUtils.cloneBean(activity);

			} catch (Exception e) {
				e.printStackTrace();
			}
			bizActivity.setCityName(shop.getCityName());
			bizActivity.setCity(shop.getCity());
			activityShop.actiivtyShops = new ArrayList<BizActivityShopDomain>();
			activityShop.actiivtyShops.add(shop);
			activityShop.activity = bizActivity;

			data.put(shop.getCityName(), activityShop);
		}

	}

	public void save() {
		try {
			Iterator<?> iterator = data.entrySet().iterator();
			List<BaseCityDomain> retCityList = cityService.findAll();
			while (iterator.hasNext()) {
				Entry<?, ?> e = (Entry<?, ?>) iterator.next();
				String key = (String) e.getKey();
				ActivityShop activityShop = (ActivityShop) e.getValue();
				BizActivityDomain bizActivity = activityShop.activity;
				ArrayList<BizActivityShopDomain> shops = activityShop.actiivtyShops;
				
				if (key == null) {
					if ((data.size() == 1) && ((null == shops) || (null != shops && shops.size() < 1))) {
						for (BaseCityDomain baseCityDomain : retCityList) {
							ActivityShop tmpShop = (ActivityShop) e.getValue();
							BizActivityDomain tmpActivity = tmpShop.activity;
							tmpActivity.setCity(baseCityDomain.getCode());
							tmpActivity.setCityName(baseCityDomain.getName());
//							Map<String, Object> retM = activityService.saveOrUpdate(tmpActivity);
							deployRDao.addDeploy(DeployType.Activity, activityService.saveOrUpdateBySid(tmpActivity));
						}
						continue;
					} else {
						// 属于有多个商户活动情况
						continue;
					}
				}
				
				System.err.println("-------------------------保存-------------" + bizActivity.getCityName() + "::"
						+ bizActivity.getCity() + "::" + bizActivity.getCampCat() + "::商户数::" + shops.size());
				bizActivity.setShopCount((long) shops.size());
				Map<String, Object> retMap = activityService.saveOrUpdate(bizActivity);
				String retCode = (String) retMap.get(Globals.GLOBAL_SERVICE_RET_CODE);
				for (int i = 0; i < shops.size(); i++) {
					BizActivityShopDomain shop = shops.get(i);
					Long retShopId = null;
					if (retCode.equals(Globals.GLOBAL_SERVICE_CODE_EXIST)) {
						shop.setActivityId((Long) retMap.get(Globals.GLOBAL_SERVICE_RET_ID));
						Map<String, Object> retShopMap = shopService.saveOrUpdate(shop);
						String retShopCode = (String) retShopMap.get(Globals.GLOBAL_SERVICE_RET_CODE);
						
						//活动商家不存在  加入未匹配队列
						if (retShopCode.equals(Globals.GLOBAL_SERVICE_CODE_NOTEXIST)) {
							matchRDao.addDiscountShop(DiscountType.Activity,
									(Long) retShopMap.get(Globals.GLOBAL_SERVICE_RET_ID));
						} 
						//存在时加入待上架队列
						else {
							deployRDao.addDeploy(DeployType.ActivityShop, (Long) retShopMap.get(Globals.GLOBAL_SERVICE_RET_ID));
						}
					} else {
						shop.setActivityId(bizActivity.getId());
						retShopId = shopService.save(shop);
						matchRDao.addDiscountShop(DiscountType.Activity, retShopId);
					}
					bizActivity.setStart(bizActivity.getStart() == null ? shop.getStart()
							: ((shop.getStart() == null) ? bizActivity.getStart()
									: (bizActivity.getStart().getTime() < shop.getStart().getTime() ? bizActivity
											.getStart() : shop.getStart())));
					bizActivity.setEnd(bizActivity.getEnd() == null ? shop.getEnd()
							: ((shop.getEnd() == null) ? bizActivity.getEnd() : (bizActivity.getEnd().getTime() > shop
									.getEnd().getTime() ? bizActivity.getEnd() : shop.getEnd())));
				}
				// update date
				BizActivityDomain updatedomain = new BizActivityDomain();
				updatedomain.setStart(bizActivity.getStart());
				updatedomain.setEnd(bizActivity.getEnd());
				activityService.update(updatedomain, new BizCondition().put("_id", bizActivity.getId()));
				log.info("处理完毕");

			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 解析 周期
	 * 
	 * @param content
	 * @return
	 */
	public Integer parseDayOfWeek(String content) {
		content = content.trim();
		if (content.equals("mon")) {
			return 1;
		} else if (content.equals("tue")) {
			return 2;
		} else if (content.equals("wed")) {
			return 3;
		} else if (content.equals("thu")) {
			return 4;
		} else if (content.equals("fri")) {
			return 5;
		} else if (content.equals("sat")) {
			return 6;
		} else if (content.equals("sun")) {
			return 7;
		} else {
			return null;
		}
	}

}
